package pers.ht.mbpo.dao;

import pers.ht.mbpo.bean.Admin;
import pers.ht.mbpo.util.DBUtil;
import pers.ht.mbpo.util.DaoUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class AdminDao {
    //添加
    public void insert(Admin a) {
        String sql = "INSERT INTO admin(username,password,nickname) VALUES (?,?,?)";
        DaoUtil.update(sql, a.getUsername(), a.getPassword(), a.getNickname());
    }

    //删除
    public void delete(String id) {
        String sql = "DELETE FROM admin WHERE username = ?";
        DaoUtil.update(sql, id);
    }

    //修改
    public void edit(Admin a) {
        String sql = "UPDATE admin SET password = ?,nickname = ? WHERE username = ?";
        DaoUtil.update(sql, a.getPassword(), a.getNickname(), a.getUsername());
    }

    //校验主键唯一
    public boolean checkId(String id) {
        return DaoUtil.checkId("admin", "username", id);
    }

    //查询所有
    public List<Admin> query() {
        List<Admin> admins = new ArrayList<Admin>();
        String sql = "SELECT * from admin WHERE 1=1";
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while (rs.next()) {
                Admin a = new Admin();
                a.setUsername(rs.getString("username"));
                a.setPassword(rs.getString("password"));
                a.setNickname(rs.getString("nickname"));
                admins.add(a);
            }
            DBUtil.close(rs, stat, conn);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        return admins;
    }

    //按主键查询一个
    public Admin queryOne(String username) {
        Admin a = new Admin();
        String sql = "SELECT * from admin WHERE username = '" + username + "'";
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            stat = conn.createStatement();
            rs = stat.executeQuery(sql);
            while (rs.next()) {
                a.setUsername(rs.getString("username"));
                a.setPassword(rs.getString("password"));
                a.setNickname(rs.getString("nickname"));
            }
            DBUtil.close(rs, stat, conn);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        return a;
    }
    //重置密码
    public void reSetPwd(String id) {
        String sql = "UPDATE admin SET password = ?  WHERE username = ?";
        DaoUtil.update(sql, id, id);
    }
}
